const electron = require('electron')
const net = require('net')
const path = require('path')
const C = require('./config')
const server = net.createServer()
const {app, BrowserWindow, ipcMain,} = electron
let mainWindow
/* eslint-disable no-console */
function createWindow() {
    mainWindow = new BrowserWindow({
        width: 800,
        height: 600,
        show: false,
        webPreferences: {
            webSecurity: false
        },
    })
    mainWindow.loadURL(`file://${__dirname}/index.html`)
    mainWindow.setMenu(null)
    if (C.mode === 'development')
        mainWindow.webContents.openDevTools()
    mainWindow.on('ready-to-show', () => {
        mainWindow.show()
    })
    mainWindow.on('closed', () => {
        mainWindow = null
    })
}
let socket = null
let carsocket = null
let javaServer = null
let javaCarServer = null
let openDoor = '00'


// 忽略证书相关错误
app.commandLine.appendSwitch('ignore-certificate-errors')
app.on('ready', function () {
    createWindow()
    server.on('connection', function (thatSocket) {
        socket = thatSocket
        // console.log('got a new connection')
        thatSocket.on('data', function (data) {
            if (!data.toString())
                return thatSocket.write('0\n')
            const stuinfo = data.toString().split(':')
            if (stuinfo.length === 2 && stuinfo[1] === 'ok'){
                thatSocket.write(`${openDoor}\n`)
                openDoor = openDoor === '11' ? '00': '00'
                return
            }
            if (stuinfo.length < 4)
                return thatSocket.write('0\n')
            const info = {
                deviceid: stuinfo[1],
                cardid: stuinfo[2],
                address: stuinfo[3],
                name: stuinfo[4]
            }
            mainWindow.webContents.send('updateReady', info)
        })
        thatSocket.on('close', function () {
            console.log('connection closed')
            socket = null
        })
        thatSocket.on('error', function () {
            console.log('connection error')
            socket = null
        })
    })
    server.on('error', function (err) {
        console.log('Server error:', err.message)
    })
    server.on('close', function () {
        console.log('Server closed')
        javaServer && javaServer.kill('SIGINT')
        javaCarServer && javaCarServer.kill('SIGINT')
    })
    server.listen(8006)
    if (C.debugLevel.buildInTcp === true) {
        const filePath = C.mode === 'development'
            ? 'JavaTcpDemo.jar'
            : path.resolve(path.dirname(process.execPath), './resources/app.asar.unpacked/JavaTcpDemo.jar')
        javaServer = require('child_process').spawn('java', [
            '-jar', filePath,
        ], {
            stdio: ['pipe', 'pipe', 'pipe',]
        })
        if (C.mode === 'development') {
            javaServer.stdout.on('data', (data) => {
                console.log(`stdout: ${data}`)
            })
            javaServer.stderr.on('data', (data) => {
                console.log(`stderr: ${data}`)
            })
            javaServer.on('close', (code) => {
                console.log(`exit code：${code}`)
            })
        }
    }
    createTcpServer()
})
ipcMain.on('quitAndInstall', (event, arg) => {
    if(socket)
        socket.write(arg)
    event.returnValue = 'pong'
})
ipcMain.on('isOpenTheCarDoor', (event, arg) => {
    if(carsocket)
        carsocket.write(arg)
    event.returnValue = 'pong'
})
ipcMain.on('openTheDoor', (event) => {
    openDoor = '11'
    event.returnValue = 'pong'
})
// 当全部窗口关闭时退出。
app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit() } })
app.on('activate', () => { if (mainWindow === null) { createWindow() } })
const createTcpServer = () =>{
    const carServer = net.createServer()
    carServer.on('connection', function (thatSocket) {
        carsocket = thatSocket
        console.log('got a new connection car')
        thatSocket.on('data', function (data) {
            mainWindow.webContents.send('carHeartBeat', data.toString())
            console.log('carHeartBeat')
        })
        thatSocket.on('close', function () {
            console.log('connection closed car')
        })
        thatSocket.on('error', function () {
            console.log('connection error car')
        })
    })
    carServer.on('error', function (err) {
        console.log('Car Server error:', err.message)
    })
    carServer.on('close', function () {
        console.log('Car Server closed')
    })
    carServer.listen(8007)
    openJavaDll()
}
const openJavaDll = ()=>{
    if (C.debugLevel.buildInTcpCar === true) {
        const filePath = C.mode === 'development'
            ? './dll'
            : path.resolve(path.dirname(process.execPath), './resources/app.asar.unpacked/dll/')
        javaCarServer = require('child_process').spawn('java', [
            '-Dfile.encoding=UTF-8',
            '-cp',
            '.;jna-3.5.1.jar;jna-platform-4.1.0.jar',
            '-jar',
            'iceDemo_64.jar',
            '192.168.0.168'
        ], {
            stdio: ['pipe', 'pipe', 'pipe',],
            cwd: filePath
        })
        if (C.mode === 'development') {
            javaCarServer.stdout.on('data', (data) => {
                console.log(`stdout: ${data}`)
            })
            javaCarServer.stderr.on('data', (data) => {
                console.log(`stderr: ${data}`)
            })
            javaCarServer.on('close', (code) => {
                console.log(`exit code：${code}`)
            })
        }
    }
}
